<template>
  <div class="base-chart" ref="chartRef" :style="{ height: computedHeight + 'px' }"></div>
</template>

<script setup>
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts/core'
import { BarChart, LineChart, PieChart, RadarChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  DatasetComponent,
  VisualMapComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  BarChart,
  LineChart,
  PieChart,
  RadarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  DatasetComponent,
  VisualMapComponent,
  CanvasRenderer
])

const props = defineProps({
  option: {
    type: Object,
    required: true
  },
  height: {
    type: Number,
    default: 220
  }
})

const chartRef = ref(null)
const computedHeight = ref(props.height)
let chartInstance = null
let resizeObserver = null

const initChart = () => {
  if (!chartRef.value) return
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }
  chartInstance.setOption(props.option, true)
}

const handleResize = () => {
  chartInstance?.resize()
}

const setupObserver = () => {
  if (!chartRef.value) return
  resizeObserver = new ResizeObserver(entries => {
    for (const entry of entries) {
      const { height } = entry.contentRect
      if (height > 0) {
        computedHeight.value = height
        chartInstance?.resize()
      }
    }
  })
  resizeObserver.observe(chartRef.value)
}

onMounted(() => {
  initChart()
  setupObserver()
  window.addEventListener('resize', handleResize)
})

watch(
  () => props.option,
  () => {
    initChart()
  },
  { deep: true }
)

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  resizeObserver?.disconnect()
  chartInstance?.dispose()
  chartInstance = null
})
</script>

<style scoped>
.base-chart {
  width: 100%;
}
</style>

